package com.midea.thread;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @description：CAS操作可能会带来ABA问题
 * @author: wangwl23
 * @create: 2021-08-08 18:18
 */
public class CasABADemo {
    public static AtomicInteger a = new AtomicInteger(1);

    public static void main(String[] args) {
        Thread main = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    int expectNum = a.get();
                    int newNum = expectNum + 1;
                    Thread.sleep(1000);//主线程休眠一秒钟，让出cpu
                    boolean isCasSuccess = a.compareAndSet(expectNum, newNum);
                    System.out.println("操作线程" + Thread.currentThread().getName() + ".cas操作:" + isCasSuccess);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        }, "主线程");

        Thread other = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(20);//确保主线程优先执行

                    a.incrementAndGet();//a +1,a=2
                    System.out.println("操作线程" + Thread.currentThread().getName() + "【increment】，值=" + a.get());
                    a.decrementAndGet();//a -1,a=1
                    System.out.println("操作线程" + Thread.currentThread().getName() + "【decrement】，值=" + a.get());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        }, "干扰线程");

        main.start();
        other.start();
    }
}
